<template>
  <div id="tou">
    <van-nav-bar
      title="信息框"
      left-text="返回"
      right-text="清空"
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
    />
  </div>
  <div id="ul">
    <ul ref="ull">
      <li v-for="(item, index) in list" :key="index">
        <span :class="{ actv: item.flag }">{{ item.mgs }}</span>
      </li>
    </ul>
  </div>
  <div id="chatk">
    <van-field
      v-model="sms"
      center
      clearable
      placeholder="请输入消息"
      @keydown.enter="fashon"
    >
      <template #button>
        <van-button size="small" type="primary" @click="fashon"
          >发送</van-button
        >
      </template>
    </van-field>
  </div>
</template>
<script>
import { useRouter } from "vue-router";
import { reactive, onMounted, ref } from "vue";
export default {
  data() {
    return {};
  },
  setup() {
    let list = reactive([]);
    const sms = ref("");
    const route = useRouter();
    let smsdb = "";
    let ws = new WebSocket("ws://121.5.18.75:8080");
    onMounted(() => {
      // 创建连接
      let ws = new WebSocket("ws://121.5.18.75:8080");
      // 连接上以后做的事情
      ws.onopen = function () {
        console.log("Connection open ...");
        // 往后端发内容
        // ws.send("nihao");
      };
      // 接受到后端发的信息时做的事
      ws.onmessage = function (ev) {
        if (smsdb !== ev.data) {
          list.push(reactive({ flag: 1, mgs: ev.data }));
          document.documentElement.scrollTop = 5000;
        }
        document.documentElement.scrollTop = 5000;
        // 主动断开
        // ws.close();
      };
      // 断开时做的事情
      ws.onclose = function () {
        console.log("Connection closed.");
      };
    });
    const fashon = () => {
      if (sms.value !== "") {
        list.push(reactive({ flag: 0, mgs: sms.value }));
        ws.send(sms.value);
        smsdb = sms.value;
        sms.value = "";
      }
    };
    const onClickLeft = () => route.go(-1);
    const onClickRight = () => {
      list.length = 0;
    };
    return {
      list,
      onMounted,
      fashon,
      sms,
      smsdb,
      ws,
      onClickLeft,
      onClickRight,
    };
  },
};
</script>

<style lang="less" scoped>
#ul {
  width: 100%;
  min-height: calc(100% - 100px);
  position: absolute;
  top: 45px;
  background: lightblue;
  overflow: hidden;
  ul {
    display: flex;
    flex-direction: column;
    li {
      flex-shrink: 0;
      width: 100%;
      height: 50px;
      position: relative;
      font-size: 20px;
      span {
        display: inline-block;
        background: white;
        border-radius: 5px;
        padding: 3px;
        margin: 5px;
      }
    }
  }

  .actv {
    color: white;
    position: absolute;
    right: 0;
    background: green;
  }
}
#tou {
  position: fixed;
  top: 0;
  background: white;
  z-index: 999;
  width: 100%;
  height: 50px;
}
#chatk {
  width: 100%;
  height: 50px;
  position: fixed;
  bottom: 0;
  background: white;
  z-index: 999;
}
</style>
